package com.woniu.woniuYoga.comm.web.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.woniuYoga.comm.core.exception.WoniuExceptionCode;
import com.woniu.woniuYoga.comm.core.exception.WoniuJsonException;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.OutputStream;

/**
 * @author: 付宽成
 * @description: json装换工具类
 * @date: 2020/8/25 11:10
 * @version: 1.0
 */
@Slf4j
public class JsonUtil {
    public static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 对象转为 json 字符串
     *
     * @param object 对象
     * @return json 字符串
     */
    public static String toJsonString(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            log.error("出现异常 code:{},message:{},class:{}", 500, e.getMessage(), e.getClass().getName());
            throw new WoniuJsonException(WoniuExceptionCode.JSON_PARSE);
        }
    }

    /**
     * 对象转为 json 字符数组
     *
     * @param object 对象
     * @return json 字符数组
     */
    public static byte[] toJsonBytes(Object object) {
        try {
            return objectMapper.writeValueAsBytes(object);
        } catch (JsonProcessingException e) {
            log.error("出现异常 code:{},message:{},class:{}", 500, e.getMessage(), e.getClass().getName());
            throw new WoniuJsonException(WoniuExceptionCode.JSON_PARSE);
        }
    }

    /**
     * 对象转为 json 字符串 ,并输出到前端
     *
     * @param object 对象
     * @return json 字符串
     */
    public static void toJsonStringWrite(OutputStream out, Object object) {
        try {
            objectMapper.writeValue(out,object);
        } catch (IOException e) {
            log.error("出现异常 code:{},message:{},class:{}", 500, e.getMessage(), e.getClass().getName());
            throw new WoniuJsonException(WoniuExceptionCode.JSON_PARSE);
        }
    }

}
